//
//  YBAssetsDetailViewController.m
//  Nectar
//
//  Created by famer on 2023/11/11.
//  Copyright © 2023 asance. All rights reserved.
//

#import "YBAssetsDetailViewController+LayoutConstraints.h"
#import "RevDataGetMyTransactions.h"
#import "YBAssetsDetailTableViewCell.h"
#import "YBAssetsDetailResultViewController.h"

@interface YBAssetsDetailViewController () <UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate>


@property (nonatomic, strong) UIView *bottomSliderView;
@property (nonatomic, strong) NSMutableArray *allDataSource;
@property (nonatomic, strong) NSMutableArray *outDataSource;
@property (nonatomic, strong) NSMutableArray *inDataSource;
@property (nonatomic, strong) NSMutableArray *failDataSource;

@end

@implementation YBAssetsDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _inOrOut = @"";
    self.view.backgroundColor = kWhiteColor;
    
    [self.view addSubview:self.navigationBar];
    [self.view addSubview:self.contentView];
    [self.contentView addSubview:self.topTabbar];
    [self.contentView addSubview:self.myScrollView];
    
    [self.myScrollView addSubview:self.allTableView];
    [self.myScrollView addSubview:self.outTableView];
    [self.myScrollView addSubview:self.inTableView];
    [self.myScrollView addSubview:self.failTableView];
    
    [self setLayoutConstraints];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [self.navigationBar resetBarItemState];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    [self getMyTransactions];
}

#pragma mark Private Mothed

- (void)toPageIndex:(NSInteger)pageIndex{
    CGFloat targetOffsetX = self.myScrollView.width * pageIndex;
    [self.myScrollView setContentOffset:CGPointMake(targetOffsetX, 0) animated:YES];
    
    if(pageIndex == 0){
        self.inOrOut = @"";
        
    } else if(pageIndex == 1){
        self.inOrOut = @"out";
        
    } else if(pageIndex == 2){
        self.inOrOut = @"in";
        
    }else {
        self.inOrOut = @"fail";
    }
    
    [self getMyTransactions];
}

- (void)getMyTransactions{
    [SVProgressHUD show];
    self.view.userInteractionEnabled = NO;
    NSMutableDictionary *params = [NSDictionary baseReqParams];
    [params setObject:@"" forKey:@"inOrOut"];
    [params setObject:self.coinType forKey:@"coinType"];
    
    NSString *urlString = [NSString stringWithFormat:@"%@",PathGetMyTransactions];
    
    [[YBHttpRequestManager shareInstance] Post:urlString params:params success:^(NSObject *resultObject) {
        NSLog(@"getMyTransactions: %@",resultObject);
        
        self.view.userInteractionEnabled = YES;
        [SVProgressHUD dismiss];
        
        //判断网络是否返回错误信息
        YBResponseModel *obj = [YBResponseModel initWithResponseObject:(NSDictionary *)resultObject];
        if([obj success]){
            NSArray *list = [RevDataGetMyTransactions mj_objectArrayWithKeyValuesArray:obj.data];
            
            for(int i=0;i<list.count;i++){
                RevDataGetMyTransactions *item = [list objectAtIndex:i];
                [item calculaeCellHeight];
            }
            
            if([self.topTabbar getCurrentIndex] == 0){
                [self.allDataSource removeAllObjects];
                [self.allDataSource addObjectsFromArray:list];
                
                //测试
                if(list.count==0){
                    RevDataGetMyTransactions *item1 = [[RevDataGetMyTransactions alloc] init];
                    [item1 setAmount:@"3443"];
                    [item1 setTxid:@"0.2"];
                    [item1 setAddress:@"8482"];
                    [item1 setStatus:@"fail"];
                    [item1 setCreateTime:@"isdfasdfan"];
                    [item1 setSymbol:@"setSymbol"];
                    [item1 setInOrOut:@"out"];

                    RevDataGetMyTransactions *item2 = [[RevDataGetMyTransactions alloc] init];
                    [item2 setAmount:@"3443"];
                    [item2 setTxid:@"setTxid"];
                    [item2 setAddress:@"8482"];
                    [item2 setStatus:@"succe"];
                    [item2 setCreateTime:@"isdfasdfan"];
                    [item2 setSymbol:@"setSymbol"];
                    [item2 setInOrOut:@"in"];

                    [self.allDataSource addObject:item1];
                    [self.allDataSource addObject:item2];

                }
                
                [self.allTableView reloadData];
                
            } else if([self.topTabbar getCurrentIndex] == 1){
                [self.outDataSource removeAllObjects];
                for(int i=0;i<list.count;i++){
                    RevDataGetMyTransactions *item = list[i];
                    if([[item.status lowercaseString] containsString:@"out"]){
                        [self.outDataSource addObject:item];
                    }
                }
                [self.outTableView reloadData];
                
            } else if([self.topTabbar getCurrentIndex] == 2){
                [self.inDataSource removeAllObjects];
                for(int i=0;i<list.count;i++){
                    RevDataGetMyTransactions *item = list[i];
                    if([[item.status lowercaseString] containsString:@"in"]){
                        [self.inDataSource addObject:item];
                    }
                }
                [self.inTableView reloadData];
                
            }else {
                [self.failDataSource removeAllObjects];
                for(int i=0;i<list.count;i++){
                    RevDataGetMyTransactions *item = list[i];
                    if([[item.status lowercaseString] containsString:@"fail"]){
                        [self.failDataSource addObject:item];
                    }
                }
                [self.failTableView reloadData];
            }
        }
        
    } failure:^(NSError *error) {
        self.view.userInteractionEnabled = YES;
        YBErrorModel *yerror = [YBErrorModel ErrorObjForNSError:error];
    }];
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if([self.topTabbar getCurrentIndex] == 0){
        return self.allDataSource.count;
        
    } else if([self.topTabbar getCurrentIndex] == 1){
        return self.outDataSource.count;

    } else if([self.topTabbar getCurrentIndex] == 2){
        return self.inDataSource.count;
        
    }else {
        return self.failDataSource.count;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 64;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *identifier = @"YBAssetsDetailTableViewCell";
    YBAssetsDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if([self.topTabbar getCurrentIndex] == 0){
        RevDataGetMyTransactions *data = self.allDataSource[indexPath.row];
        [cell setData:data];
        
    } else if([self.topTabbar getCurrentIndex] == 1){
        RevDataGetMyTransactions *data = self.outDataSource[indexPath.row];
        [cell setData:data];
        
    } else if([self.topTabbar getCurrentIndex] == 2){
        RevDataGetMyTransactions *data = self.inDataSource[indexPath.row];
        [cell setData:data];
        
    }else {
        RevDataGetMyTransactions *data = self.failDataSource[indexPath.row];
        [cell setData:data];
    }
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    RevDataGetMyTransactions *data = nil;
    if([self.topTabbar getCurrentIndex] == 0){
        data = self.allDataSource[indexPath.row];
        
    } else if([self.topTabbar getCurrentIndex] == 1){
        data = self.outDataSource[indexPath.row];
        
    } else if([self.topTabbar getCurrentIndex] == 2){
        data = self.inDataSource[indexPath.row];
        
    }else {
        data = self.failDataSource[indexPath.row];
    }
    
    YBAssetsDetailResultViewController *viewcontroller = [[YBAssetsDetailResultViewController alloc] init];
    viewcontroller.data = data;
    viewcontroller.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:viewcontroller animated:YES];
}

#pragma mark - UITabBarControllerDelegate

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
    // 根据选中的标签更新底部滑块的位置
    NSUInteger selectedIndex = [tabBarController.viewControllers indexOfObject:viewController];
    CGFloat itemWidth = tabBarController.tabBar.frame.size.width / tabBarController.viewControllers.count;
    CGFloat newPosition = selectedIndex * itemWidth;
    
    [UIView animateWithDuration:0.3 animations:^{
        CGRect frame = self.bottomSliderView.frame;
        frame.origin.x = newPosition;
        self.bottomSliderView.frame = frame;
    }];
}

#pragma mark UIScrollViewDelegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if([scrollView isEqual:self.myScrollView]){
        NSInteger pageIndex = fabs(scrollView.contentOffset.x)/scrollView.width;
        [self.topTabbar setCurrentIndex:pageIndex];
        
        [self getMyTransactions];
    }
}

#pragma mark - Getter Setter
YBViewGetter(contentView, _contentView, kThemeBackground);
- (YBAssetsDetailTabbar *)topTabbar{
    if(!_topTabbar){
        _topTabbar = [[YBAssetsDetailTabbar alloc] initWithFrame:CGRectZero];
        _topTabbar.backgroundColor = kWhiteColor;
        __weak __typeof(&*self)weakSelf = self;
        _topTabbar.actionBlock = ^(NSString *button, NSInteger pageIndex) {
            NSLog(@"%@", button);
            __strong __typeof(&*weakSelf)strongSelf = weakSelf;
            if(!strongSelf) return;
            CGFloat targetOffsetX = self.myScrollView.width * pageIndex;
            [strongSelf.myScrollView setContentOffset:CGPointMake(targetOffsetX, 0) animated:NO];
            
            [strongSelf getMyTransactions];
        };
    }
    return _topTabbar;
}

- (YBNavigationBar *)navigationBar{
    if(!_navigationBar){
        _navigationBar = [[YBNavigationBar alloc] initWithFrame:CGRectZero];
        _navigationBar.backgroundColor = kWhiteColor;
        [_navigationBar setTitle:@"USDT" titleColor:kThemeBlackColor];
        [_navigationBar setLeftBarImage:@"icon_nav_back" forState:UIControlStateNormal];
        __weak __typeof(&*self)weakSelf = self;
        _navigationBar.onLeftBarButtonBlock = ^(){
            __strong __typeof(&*weakSelf)strongSelf = weakSelf;
            if(!strongSelf) return;
            
            [strongSelf.navigationController popViewControllerAnimated:YES];
        };
    }
    return _navigationBar;
}

- (UITableView *)allTableView{
    if(!_allTableView){
        _allTableView = [self generateTableView];
    }
    return _allTableView;
}

- (UITableView *)outTableView{
    if(!_outTableView){
        _outTableView = [self generateTableView];
    }
    return _outTableView;
}

- (UITableView *)inTableView{
    if(!_inTableView){
        _inTableView = [self generateTableView];
    }
    return _inTableView;
}

- (UITableView *)failTableView{
    if(!_failTableView){
        _failTableView = [self generateTableView];
    }
    return _failTableView;
}

- (UITableView *)generateTableView{
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    tableView.backgroundColor = kClearColor;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.delegate = self;
    tableView.dataSource = self;
    
    [tableView registerClass:[YBAssetsDetailTableViewCell class] forCellReuseIdentifier:@"YBAssetsDetailTableViewCell"];
    
    return tableView;
}

- (UIScrollView *)myScrollView{
    if(!_myScrollView){
        _myScrollView = [[UIScrollView alloc] initWithFrame:CGRectZero];
        _myScrollView.pagingEnabled = YES;
        _myScrollView.delegate = self;
        _myScrollView.showsVerticalScrollIndicator = NO;
        _myScrollView.showsHorizontalScrollIndicator = NO;
        _myScrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0); // 设置左右两侧留白
        
        if (@available(iOS 11.0, *)) {
            _myScrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return _myScrollView;
}

- (NSMutableArray *)allDataSource{
    if(!_allDataSource){
        _allDataSource = [[NSMutableArray alloc] init];
    }
    return  _allDataSource;
}

- (NSMutableArray *)outDataSource{
    if(!_outDataSource){
        _outDataSource = [[NSMutableArray alloc] init];
    }
    return  _outDataSource;
}

- (NSMutableArray *)inDataSource{
    if(!_inDataSource){
        _inDataSource = [[NSMutableArray alloc] init];
    }
    return  _inDataSource;
}

- (NSMutableArray *)failDataSource{
    if(!_failDataSource){
        _failDataSource = [[NSMutableArray alloc] init];
    }
    return  _failDataSource;
}

@end
